// import 'package:flutter_alpha_player_plugin/alpha_player_controller.dart';
import 'package:flutter_cache_manager/file.dart';
import 'package:flutter_svgaplayer3/flutter_svgaplayer3.dart';
import 'package:get/get.dart';
import 'package:love_newf/app/com/model/room_data_model.dart';
import 'package:love_newf/app/com/model/room_prop_model.dart';
import 'package:love_newf/app/com/util/gift_utils.dart';
import 'package:love_newf/app/com/util/my_toast.dart';

class GiftPropAnimationLogic extends GetxController {
  List<RoomDataGivePropMsg> giftList = [];
  bool playing = false;

  ///是否是svga ，礼物有svga 和MP4
  bool isSvga = false;
  late SVGAAnimationController animationController;

  play(RoomDataGivePropMsg model) {
    giftList.add(model);
    //没有播放
    if (!playing) {
      nextPlay();
    }
  }

  nextPlay() async {
    if (giftList.isEmpty) {
      playing = false;
      update();
    }
    playing = true;
    RoomDataGivePropMsg model = giftList[0];
    giftList.removeAt(0);
    try {
      RoomPropModel? propModel = await GiftUtils.getPropAsync(model.propId);
      if (propModel == null) {
        nextPlay();
        return;
      }
      File? file = await GiftUtils.getEffectFile(propModel.id);
      if (file == null) {
        toastError("礼物下载失败${model.propId}");
        nextPlay();
        return;
      }
      if (propModel.effectUrl.endsWith(".svga")) {
        isSvga = true;
        playSvga(file);
      } else {
        isSvga = false;
        // playMp4(file);
      }
      update();
    } catch (e) {
      print(e);
      nextPlay();
    }
  }

  playSvga(File file) async {
    final videoItem =
        await SVGAParser.shared.decodeFromBuffer(await file.readAsBytes());
    animationController.videoItem = videoItem;
    animationController
        .forward() // Try to use .forward() .reverse()
        .whenComplete(() {
      animationController.videoItem = null;
      nextPlay();
    }).catchError((e) {
      nextPlay();
    });
  }

  playMp4(File file) async {
    // AlphaPlayerController.setAlphaPlayerCallBack(
    //   ///播放结束回调
    //   endAction: () {
    //     // ///移除视图
    //     // AlphaPlayerController.detachView();
    //     //
    //     // ///释放播放器
    //     // AlphaPlayerController.releasePlayer();
    //     // nextPlay();
    //   },
    //
    //   ///播放开始回调
    //   startAction: () {},
    //
    //   ///播放器监听
    //   monitorCallbacks: (expand) {},
    //
    //   ///视频尺寸变化回调
    //   onVideoSizeChanged: (expand) {},
    //
    //   ///扩展回调
    //   platformCallback: (ex) {
    //     toast("message $ex");
    //   },
    // );

    var dir = file.dirname;
    var name = file.basename;
    // var result = await AlphaPlayerController.playVideo(dir, name,
    //     portraitPath: 1, landscapePath: 8);
    //
    // ///添加视图
    // AlphaPlayerController.attachView();
  }
}
